package com.shuai.user.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import com.shuai.common.constant.EmailConstant;
import com.shuai.common.utils.EmailCodeUtils;
import com.shuai.user.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
@Slf4j
public class EmailServiceImpl implements EmailService {

    /**
     * 验证码发送服务
     */
    @Autowired
    private JavaMailSender javaMailSender;


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${spring.mail.username}")
    private String fromUser;


    /**
     * 发送验证码
     *
     * @param toUser 接收用户
     */
    @Override
    public void sendCodeToUser(String toUser) throws MessagingException {
        // 调用验证码服务发送验证码
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        mimeMessage.setFrom(fromUser);
        String code = EmailCodeUtils.generateCode();
        String text = EmailConstant.PROMPT + code + EmailConstant.WARNING;
        mimeMessage.setSubject(EmailConstant.SUBJECT);
        mimeMessage.setText(text);
        mimeMessage.setRecipients(Message.RecipientType.TO, toUser);
        javaMailSender.send(mimeMessage);
        redisTemplate.opsForValue().set(EmailConstant.USER_EMAIL_KEY + ":" + toUser, code,
                EmailConstant.TIME_OUT, EmailConstant.TIME_UNIT);
    }

    /**
     * 获取指定用户的验证码
     */
    @Override
    public String getEmailCode(String email) {
        String emailCode = redisTemplate.opsForValue().get(EmailConstant.USER_EMAIL_KEY + ":" + email);
        log.info("\n\n用户：{}校验了邮箱验证码{}\n\n", email, StringUtils.isBlank(emailCode) ? "null" : emailCode);
        return emailCode;
    }

    @Override
    public void removeEmailCode(String email) {
        redisTemplate.delete(EmailConstant.USER_EMAIL_KEY + ":" + email);
    }

    @Override
    public boolean validateEmailCode(String email, String code) {
        String codeSent = redisTemplate.opsForValue().get(EmailConstant.USER_EMAIL_KEY + ":" + email);
        return !CharSequenceUtil.isBlank(codeSent) && codeSent.equals(code);
    }

}
